package com.cby.android.sample.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.cby.android.olive.ext.dp
import com.cby.android.olive.ext.getScreenWidth
import com.cby.android.sample.R
import com.cby.android.sample.bean.MetaImageBean
import com.cby.android.sample.constant.MetaConstant

/**
 * Meta 的图片列表适配器
 * @author chenbaoyang
 */
class MetaImageAdapter(private val context: Context) :
    RecyclerView.Adapter<MetaImageAdapter.MetaImageViewHolder>() {

    var currentType = MetaConstant.META_IMAGE_TYPE_LINEAR

    private val dataList = mutableListOf<MetaImageBean>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        MetaImageViewHolder(
            LayoutInflater.from(context).inflate(R.layout.item_meta_image, parent, false))

    override fun getItemCount() = dataList.size

    override fun onBindViewHolder(holder: MetaImageViewHolder, position: Int) {
        holder.updateSize(dataList[position], currentType)
        val options = RequestOptions().apply {
            fitCenter()
            placeholder(R.drawable.loading_bixue)
            error(R.drawable.loading_bixue)
            diskCacheStrategy(DiskCacheStrategy.ALL)
        }
        Glide.with(context).load(dataList[position].img).apply(options).into(holder.image)
    }


    fun setData(list: MutableList<MetaImageBean>) {
        dataList.clear()
        dataList.addAll(list)
        notifyDataSetChanged()
    }

    fun addData(list: MutableList<MetaImageBean>) {
        dataList.addAll(list)
        notifyDataSetChanged()
    }

    fun updateImageShowType(type: Int) {
        currentType = type
        notifyDataSetChanged()
    }



    class MetaImageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val image: ImageView = itemView.findViewById(R.id.iv_meta_image)

        fun updateSize(bean: MetaImageBean, type: Int) {
            if(type == MetaConstant.META_IMAGE_TYPE_STAGE) {
                val width = itemView.context.getScreenWidth/2 - 20.dp
                //进行原图片宽高比，进行计算实际空间高度，增加一个随机高度差
                val offset = (Math.random() * 100)
                val height = (width * bean.height) / bean.width
                image.layoutParams = LinearLayout.LayoutParams(width,height)
            }
        }
    }


}